package VirtualMachines;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import Data.CarDataModel;

public class ReceiveSensor {
	static private boolean isTurnOn;
	static private List<CarDataModel> cars;
	
	public ReceiveSensor(){
		
		cars = new ArrayList<CarDataModel>();
		for(int i=0; i<3; i++){
			CarDataModel eachCar = new CarDataModel();
			eachCar.velocity = 50;
			eachCar.distanceToFront = 30;
			cars.add(eachCar);
		}
		
		isTurnOn = true;
		
		TurnOn();
	}
	
	static public void TurnOn(){
		new Thread(new Runnable() {
			public void run() {
				try {
					while(isTurnOn){
						getDataOfFrontCar();
						
//						for(int i=0; i <showReceiveSensorData().size(); i++)
//							System.out.println(showReceiveSensorData().get(i));
						Thread.sleep(1000);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}).start();
	}
	
	static public List<CarDataModel> getDataOfFrontCar(){
		List<CarDataModel> prevCarList = new ArrayList<CarDataModel>();
		
		for(int i=0; i<3; i++)
			prevCarList.addAll(cars);
		
		if(cars != null)
			cars.clear();
		try{
			for(int i = 0; i < 3; i++){
				CarDataModel eachCar = new CarDataModel();
				eachCar.distanceToFront = prevCarList.get(i).distanceToFront;
				eachCar.velocity = prevCarList.get(i).velocity;
				
				Random random = new Random();
				if(random.nextBoolean())
					eachCar.distanceToFront++;
				else
					eachCar.distanceToFront--;
				
				random = new Random();
				if(random.nextBoolean())
					eachCar.velocity++;
				else
					eachCar.velocity--;
				
				cars.add(eachCar);
			}
		}
		catch (Exception e) {
			// TODO: handle exception
//			System.out.println("before CarDataModel is init :" + e.toString());
		}
		
		return cars;
	}
	
	static public List<String> showReceiveSensorData(){
		List<String> resultList = new ArrayList<String>();
		
		try{
			for(int i=0; i<3; i++){
				String result = "velocity = " + cars.get(i).velocity + "km/h and Distance To Front Car = " + cars.get(i).distanceToFront + " in " + (i+1) + " car\n";
				resultList.add(result);
			}
		}
		catch (Exception e) {
			// TODO: handle exception
			for (int i=0; i<3; i++)
				resultList.add("");
		}
		
		return resultList;
	}
}
